package org.yzh.www.chart;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.yzh.www.utils.GenerateChartUtil;
import org.yzh.www.utils.GeneratePieChartUtil;
import org.yzh.www.utils.JFreeChartUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨振华
 * @since 2024/6/18
 **/
public class barCharts {
    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(() -> {
            // 创建窗口并添加面板
            JFrame frame = new JFrame("柱状图显示");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            try {
                // 创建工作簿对象
                Workbook workbook = new XSSFWorkbook(new FileInputStream("src/main/resources/excel/某一门课成绩.xlsx"));
                Sheet sheet = workbook.getSheetAt(0); // 假设数据在第一个Sheet中
                // 统计开课学院及其数量
                Map<String, Integer> sexCountMap = new HashMap<>();
                Map<String, Integer> scoreCountMap = new HashMap<>();
                for (Row row : sheet) {
                    if (row.getRowNum() == 0) continue; // 跳过表头行
                    cleanData(row);// 数据清洗
                    String sex = row.getCell(3).getStringCellValue(); // 假设第四列是性别
                    sexCountMap.put(sex, sexCountMap.getOrDefault(sex, 0) + 1);
                }

                // 统计分数段
                List<List<Object>> dataList  = countScoreRanges(sheet);
                //x轴名称列表
                List<String> xAxisNameList = new ArrayList<>(Arrays.asList("60-70", "71-85", "86-100"));
                //图例名称列表
                List<String> legendNameList = new ArrayList<>(sexCountMap.keySet());

                System.out.println(dataList);
                /*//数据列表
                List<List<Object>> dataList = new ArrayList<>();
                dataList.add(data);
                dataList.add(new ArrayList<>(sexCountMap.values()));*/
                //图例背景颜色
                List<Color> legendColorList = new ArrayList<>(Arrays.asList(new Color(65, 105, 225)));
                byte[] byteArray = GenerateChartUtil.createBarChart(/*response.getOutputStream(),*/ "总评成绩和男女性别关系柱状图", legendNameList, xAxisNameList
                        , dataList, JFreeChartUtil.createChartTheme("宋体"), "男女人数比例", "总评分数区间"
                        , 600, 400, 0d, 100d, legendColorList, true, "{2}%");

                // 将字节流转换为BufferedImage
                ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
                BufferedImage image = ImageIO.read(bis);

                // 创建JLabel来显示图像
                JLabel label = new JLabel(new ImageIcon(image));

                // 创建JPanel并添加标签
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());
                panel.add(label, BorderLayout.CENTER);

                frame.getContentPane().add(panel);
                frame.pack();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
                JLabel errorLabel = new JLabel("图表生成出错：" + e.getMessage());
                frame.getContentPane().add(errorLabel, BorderLayout.CENTER);
            }

            frame.setVisible(true);
        });
    }
    private static void cleanData(Row row) {
        Cell creditCell = row.getCell(6); // 学分
        Cell usualScoreCell = row.getCell(7); // 平时成绩
        Cell finalScoreCell = row.getCell(8); // 期末成绩
        Cell totalScoreCell = row.getCell(9); // 总评成绩
        Cell convertedScoreCell = row.getCell(10); // 折算成绩
        Cell highestScoreCell = row.getCell(11); // 最高成绩
        Cell makeupScoreCell = row.getCell(12); // 补考成绩
        Cell gradePointCell = row.getCell(13); // 绩点

        fillEmptyCellWithZero(creditCell);
        fillEmptyCellWithZero(usualScoreCell);
        fillEmptyCellWithZero(finalScoreCell);
        fillEmptyCellWithZero(totalScoreCell);
        fillEmptyCellWithZero(convertedScoreCell);
        fillEmptyCellWithZero(highestScoreCell);
        fillEmptyCellWithZero(makeupScoreCell);
        fillEmptyCellWithZero(gradePointCell);
    }

    private static void fillEmptyCellWithZero(Cell cell) {
        if (cell == null || cell.getCellType() == CellType.BLANK) {
            cell.setCellValue(0);
        }
    }

    /*private static List<Object> countScoreRanges(Sheet sheet) {
        int[] scoreCounts = new int[3]; // 初始化三个分数段的计数器
        for (Row row : sheet) {
            if (row.getRowNum() == 0) continue; // 跳过表头行
            String sex = row.getCell(3).getStringCellValue(); // 假设第四列是性别
            Cell totalScoreCell = row.getCell(9); // 总评成绩
            double totalScore;
            if (totalScoreCell.getCellType() == CellType.NUMERIC) {
                totalScore = totalScoreCell.getNumericCellValue();
            } else if (totalScoreCell.getCellType() == CellType.STRING) {
                try {
                    totalScore = Double.parseDouble(totalScoreCell.getStringCellValue());
                } catch (NumberFormatException e) {
                    totalScore = 0; // 如果转换失败，默认设置为0或其他合适的处理方式
                }
            } else {
                totalScore = 0; // 如果不是数字也不是字符串，按照需要处理
            }

            if (totalScore >= 60 && totalScore <= 70) {
                scoreCounts[0]++;
            } else if (totalScore > 70 && totalScore <= 85) {
                scoreCounts[1]++;
            } else if (totalScore > 85 && totalScore <= 100) {
                scoreCounts[2]++;
            }
        }

        return Arrays.stream(scoreCounts).boxed().collect(Collectors.toList());
    }*/
    private static List<List<Object>> countScoreRanges(Sheet sheet) {
        int[] scoreCounts = new int[3]; // 初始化三个分数段的计数器
        int[][] sexCounts = new int[3][2]; // 初始化三个分数段的计数器
        for (Row row : sheet) {
            if (row.getRowNum() == 0) continue; // 跳过表头行
            String sex = row.getCell(3).getStringCellValue(); // 假设第四列是性别
            Cell totalScoreCell = row.getCell(9); // 总评成绩
            double totalScore;
            if (totalScoreCell.getCellType() == CellType.NUMERIC) {
                totalScore = totalScoreCell.getNumericCellValue();
            } else if (totalScoreCell.getCellType() == CellType.STRING) {
                try {
                    totalScore = Double.parseDouble(totalScoreCell.getStringCellValue());
                } catch (NumberFormatException e) {
                    totalScore = 0; // 如果转换失败，默认设置为0或其他合适的处理方式
                }
            } else {
                totalScore = 0; // 如果不是数字也不是字符串，按照需要处理
            }

            if (totalScore >= 60 && totalScore <= 70) {
                scoreCounts[0]++;
                if ("男".equals(sex)) {
                    sexCounts[0][0]++;
                } else if ("女".equals(sex)) {
                    sexCounts[0][1]++;
                }
            } else if (totalScore > 70 && totalScore <= 85) {
                scoreCounts[1]++;
                if ("男".equals(sex)) {
                    sexCounts[1][0]++;
                } else if ("女".equals(sex)) {
                    sexCounts[1][1]++;
                }
            } else if (totalScore > 85 && totalScore <= 100) {
                scoreCounts[2]++;
                if ("男".equals(sex)) {
                    sexCounts[2][0]++;
                } else if ("女".equals(sex)) {
                    sexCounts[2][1]++;
                }
            }
        }
        // 将二维数组转换为List<List<Integer>>
        List<List<Object>> dataList = new ArrayList<>();
        System.out.println();
        dataList.add(new ArrayList<>(Arrays.asList(sexCounts[0][0], sexCounts[1][0], sexCounts[2][0])));
        dataList.add(new ArrayList<>(Arrays.asList(sexCounts[0][1], sexCounts[1][1], sexCounts[2][1])));
        return dataList;
    }
}
